package com.ruoyi.hxf.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.hxf.domain.Course;
import com.ruoyi.hxf.domain.TeacherCourse;
import com.ruoyi.hxf.domain.bo.SubjectBo;
import com.ruoyi.hxf.domain.vo.SubjectVo;
import com.ruoyi.hxf.mapper.RosterMapper;
import com.ruoyi.hxf.mapper.TypeMapper;
import com.ruoyi.hxf.service.IRosterService;
import com.ruoyi.hxf.service.ITabService;
import com.ruoyi.hxf.service.ITypeService;
import com.ruoyi.system.domain.App;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/tab/data")
public class TabController extends BaseController {
    private final RosterMapper rosterMapper;
    private final TypeMapper typeMapper;
    private final ITypeService iTypeService;
    private final ISysUserService userService;
    private final IRosterService iRosterService;
    private final ITabService iTabService;

    /**
     * 查询老师的课表
     *
     * @return
     */
    @GetMapping("")
    public List<TeacherCourse> list() {
        Long userId = LoginHelper.getUserId();
        return rosterMapper.selectTeacherOne(Long.valueOf(userId));
    }

    /**
     * 查询班级的老师信息
     *
     * @return
     */
    @GetMapping("/teacherInformation/{classId}")
    public List<SysUser> teacherInformation(@PathVariable("classId") Long classId) {
        String s = typeMapper.selectTeacherIdCount(classId);
        Long classLeader = iTypeService.selectTypeByDeptId(classId);
        List<SysUser> sysUsers = new ArrayList<>();
        sysUsers.add(userService.selectTeacherById(classLeader));
        if (s != null) {
            String[] split = s.split(",");
            for (String s1 : split) {
                if (!s1.equals(String.valueOf(classLeader)))
                    sysUsers.add(userService.selectTeacherById(Long.valueOf(s1)));
            }
        }
        return sysUsers;
    }

    /**
     * 查询班级的课表信息
     *
     * @return
     */
    @GetMapping("/classInformation/{classId}")
    public List<List<String>> classInformation(@PathVariable("classId") String classId) {
        List<List<String>> list = new ArrayList<>();
        List<Course> courses = iRosterService.listClassCourse(classId);
        for (Course course : courses) {
            List<String> list1 = new ArrayList<>();
            list1.add(course.getOneS() + "," + course.getOneT());
            list1.add(course.getTwoS() + "," + course.getTwoT());
            list1.add(course.getThreeS() + "," + course.getThreeT());
            list1.add(course.getFourS() + "," + course.getFourT());
            list1.add(course.getFiveS() + "," + course.getFiveT());
            list1.add(course.getSixS() + "," + course.getSixT());
            list.add(list1);
        }
        return list;
    }

    /**
     * 查询班级家长信息
     *
     * @param user      模糊查询
     * @param pageQuery 分页
     * @return
     */
    @GetMapping("/class/class")
    public TableDataInfo<SysUser> classParentList(SysUser user, PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        String deptId = typeMapper.selectFromClass(userId);
        if (deptId != null) {
            String classParents = typeMapper.selectClassParentByDeptId(Long.valueOf(deptId));
            if (classParents == null) {
                return null;
            } else {
                return userService.selectPageClassParentList(user, pageQuery, classParents, deptId);
            }
        }
        return null;
    }
    @GetMapping("/class/identity")
    public Boolean identity(){
        Long userId = LoginHelper.getUserId();
        return userService.selectIdentity(userId);
    }
    /**
     * 查询班级老师信息
     *
     * @param user      模糊查询
     * @param pageQuery 分页
     * @return
     */
    @GetMapping("/classTeachers/classTeachers")
    public TableDataInfo<SysUser> classTeachersList(SysUser user, PageQuery pageQuery) {
        pageQuery.setPageSize(pageQuery.getPageSize() + 1);
        Long userId = LoginHelper.getUserId();
        String deptId = typeMapper.selectFromClass(userId);
        String classTeachers = typeMapper.selectTeacherIdCount(Long.valueOf(deptId));
        TableDataInfo<SysUser> sysUserTableDataInfo = userService.selectPageClassTeachersList(user, pageQuery, classTeachers, deptId);
        List list = new ArrayList();
        if (sysUserTableDataInfo.getRows() != null) {
            for (SysUser row : sysUserTableDataInfo.getRows()) {
                if (!String.valueOf(row.getUserId()).equals(String.valueOf(userId))) {
                    row.setRemark(rosterMapper.selectUserByIdRoleName(row.getUserId()).substring(0, rosterMapper.selectUserByIdRoleName(row.getUserId()).length() - 2));
                    list.add(row);
                }
            }
            sysUserTableDataInfo.setRows(list);
            sysUserTableDataInfo.setTotal(sysUserTableDataInfo.getTotal() - 1);
        }
        return sysUserTableDataInfo;
    }

    /**
     * 踢出班级
     */
    @Log(title = "退出班级", businessType = BusinessType.UPDATE)
    @PutMapping("/deleteUserClass/{userIds}")
    @SaCheckPermission("tab:class:del")
    public R<Void> deleteUserClass(@PathVariable Long[] userIds) {

        for (Long userId : userIds) {
            String classId = userService.getUserClassId(userId);
            StringBuffer stringBuffer = new StringBuffer();
            String classParent = iTypeService.selectClassParentByDeptId(Long.valueOf(classId));
            if (classParent != null) {
                String[] split = classParent.split(",");
                for (String s : split) {
                    if (!s.equals(String.valueOf(userId))) {
                        if (stringBuffer.length() == 0) {
                            stringBuffer.append(s);
                        } else {
                            stringBuffer.append("," + s);
                        }
                    }
                }
            }
            if (stringBuffer.length() == 0) {
                iTypeService.updateClassParent(null, Long.valueOf(classId));
            } else {
                iTypeService.updateClassParent(stringBuffer.toString(), Long.valueOf(classId));
            }
            App app = new App();
            app.setUserId(userId);
            app.setClassId(null);
            app.setCreateTime(null);
            userService.updateUserClassId(app);
        }
        return R.ok();
    }

    /**
     * 查询班级的密码（班主任）
     */
    @GetMapping("/classPassword")
    public String getClassPassword() {
        Long userId = LoginHelper.getUserId();
        String classId = typeMapper.selectFromClass(userId);
        String password = null;
        if (classId != null) {
            password = iTypeService.selectPasswordByDeptId(Long.valueOf(classId));
        }
        return password;
    }

    /**
     * 设置班级密码
     */
    @Log(title = "保存班级密码", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/{classPassword}")
    public R<Void> updateClassPassword(@PathVariable("classPassword") String classPassword) {
        Long userId = LoginHelper.getUserId();
        String classId = typeMapper.selectFromClass(userId);
        String password = iTypeService.selectPasswordByDeptId(Long.valueOf(classId));
        if (password != null && classPassword.equals(password)) {
            return R.ok("验证码与原验证码重复");
        }
        if (classId != null) {
            if (classPassword.equals("null")) {
                classPassword = null;
            }
            iTypeService.updateClassPassword(classId, classPassword);
            return R.ok("修改班级验证码成功");
        }
        return toAjax(0);
    }

    /**
     * 查询班级名称
     *
     * @return
     */
    @GetMapping("/class/className")
    public String getClassName() {
        Long userId = LoginHelper.getUserId();
        String classId = typeMapper.selectFromClass(userId);
        return rosterMapper.selectClassName(Long.valueOf(classId));
    }

    /**
     * 查询班级家长和老师信息
     *
     * @return
     */
    @GetMapping("/class/{classId}")
    public List<SysUser> classList(@PathVariable("classId") String classId) {
        ArrayList<SysUser> sysUsers = new ArrayList<>();
        String classParents = typeMapper.selectClassParentByDeptId(Long.valueOf(classId));
        String classTeachers = typeMapper.selectTeacherIdCount(Long.valueOf(classId));
        System.out.println(classParents + "" + classTeachers);
        String[] split1 = classTeachers.split(",");
        if (split1.length != 0) {
            for (String s : split1) {
                sysUsers.add(userService.selectTeacherById(Long.valueOf(s)));
            }
        }
        if (classParents != null) {
            String[] split2 = classParents.split(",");
            if (split2.length != 0) {
                for (String s : split2) {
                    sysUsers.add(userService.selectParentById(Long.valueOf(s)));
                }
            }
        }

        return sysUsers;
    }
}
